package array

import (
	mgl "github.com/go-gl/mathgl/mgl32"
	"math"
)

func SetTextureCo(newpoints_ptr *[]float32,points []float32,indices []uint32,slice_len int32,xc,yc int){
	newpoints := *newpoints_ptr
	f := func (j int,key int32) float32{
		value := indices[j]
		return points[int32(value)*slice_len+key]
	}
	getVec3 := func(j int) mgl.Vec3{
		return mgl.Vec3{f(j,0),f(j,1),f(j,2)}
	}
	var getTextureCo = func(max1,max2 float64,x1,y1 float32) (float32,float32){
		var x,y float32
		if max1 == float64(x1){x = 1}else{x = 0}
		if max2 == float64(y1){y = 1}else{y = 0}
		return x,y
	}
	xn := mgl.Vec3{1,0,0}
	yn := mgl.Vec3{0,1,0}
	zn := mgl.Vec3{0,0,1}
	//计算纹理坐标
	for j:=0;j<len(indices);j+=3{
		p0 := getVec3(j)
		p1 := getVec3(j+1)
		p2 := getVec3(j+2)
		//平面法向量
		normal := p1.Sub(p0).Cross(p2.Sub(p0)).Normalize()
		if normal.Dot(p0)< 0{
			normal = normal.Mul(-1)
		}
		cosx := math.Abs(float64(normal.Dot(xn)))
		cosy := math.Abs(float64(normal.Dot(yn)))
		cosz := math.Abs(float64(normal.Dot(zn)))
		maxcos := math.Max(cosx,math.Max(cosy,cosz))
		maxX := math.Max(float64(p0.X()),math.Max(float64(p1.X()),float64(p2.X())))//x最大值
		maxY := math.Max(float64(p0.Y()),math.Max(float64(p1.Y()),float64(p2.Y())))//y最大值
		maxZ := math.Max(float64(p0.Z()),math.Max(float64(p1.Z()),float64(p2.Z())))//z最大值
		var x0,x1,x2,y0,y1,y2 float32
		if maxcos == cosx{
			x0,y0 = getTextureCo(maxY,maxZ,p0.Y(),p0.Z())
			x1,y1 = getTextureCo(maxY,maxZ,p1.Y(),p1.Z())
			x2,y2 = getTextureCo(maxY,maxZ,p2.Y(),p2.Z())
		} else if maxcos == cosy{
			x0,y0 = getTextureCo(maxX,maxZ,p0.X(),p0.Z())
			x1,y1 = getTextureCo(maxX,maxZ,p1.X(),p1.Z())
			x2,y2 = getTextureCo(maxX,maxZ,p2.X(),p2.Z())
		} else if maxcos == cosz{
			x0,y0 = getTextureCo(maxX,maxY,p0.X(),p0.Y())
			x1,y1 = getTextureCo(maxX,maxY,p1.X(),p1.Y())
			x2,y2 = getTextureCo(maxX,maxY,p2.X(),p2.Y())
		}
		newpoints[j*int(slice_len)+xc],newpoints[j*int(slice_len)+yc]			= x0,y0
		newpoints[(j+1)*int(slice_len)+xc],newpoints[(j+1)*int(slice_len)+yc] 	= x1,y1
		newpoints[(j+2)*int(slice_len)+xc],newpoints[(j+2)*int(slice_len)+yc] 	= x2,y2
	}

}
